﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Web;

namespace EMoney.IStock.Client.Framework
{
    public class SHtmlString : IHtmlString
    {
        string html = "";
        public SHtmlString()
        {

        }

        public void SetHtml(string html)
        {
            this.html = html;
        }

        public string ToHtmlString()
        {
            return html;
        }
    }

    public class StringHelper
    {
        /// <summary>
        /// 股票行情
        /// </summary>
        /// <param name="stock"></param>
        /// <param name="secuAbbr"></param>
        /// <returns></returns>
        public static IHtmlString GoKLine(string stock, string secuAbbr)
        {
            SHtmlString s = new SHtmlString();
            if (string.IsNullOrEmpty(secuAbbr))
            {
                s.SetHtml("--");
            }
            else
            {
                s.SetHtml("<a href=\"javascript:;\" onclick=\"return GoKLine('" + stock + "')\">" + secuAbbr + "</a>");
            }
            return s;
        }

        /// <summary>
        /// 获取静态文件地址
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string GetStaticFile(string file)
        {
            var str = ConfigHelper.StaticFile;
            if (str == "~/")
            {
                UrlHelper he = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
                string path = he.Content("~/" + file);
                return path;
            }
            else
            {
                return str + file;
            }
        }

        public static string GetTrendsFile(string file)
        {
            UrlHelper he = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
            string path = he.Content("~/" + file);
            return path;
        }

        /// <summary>
        /// 格式化Decimal(默认保留两位小数)
        /// </summary>
        /// <param name="d"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string FormatDecimal(decimal? d, string format = "0.00")
        {
            if (d != null)
            {
                return d.Value.ToString(format);
            }
            else
            {
                return "0.00";
            }
        }

        /// <summary>
        /// 数据大于0时红色，小于0时绿色
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="def">为0时默认值</param>
        /// <param name="format">数据格式</param>
        /// <param name="houzui">后缀</param>
        /// <param name="isnull">为空时返回内容</param>
        /// <returns></returns>
        public static IHtmlString DecimalFormatColor(decimal? obj, string def = "0.00", string format = "0.00", string houzui = "", string isnull = "--")
        {
            SHtmlString s = new SHtmlString();
            try
            {
                if (obj == null || obj.ToString() == "")
                {
                    s.SetHtml(isnull);
                    return s;
                }
                var data = Convert.ToDecimal(obj);
                var flag = false;
                if (data > 0)
                {
                    flag = true;
                }
                else if (data < 0)
                {
                    flag = false;
                }
                else
                {
                    if (def != "" && def != isnull)
                    {
                        s.SetHtml(def + houzui);
                    }
                    else
                    {
                        s.SetHtml(isnull);
                    }
                    return s;
                }
                if (flag)
                {
                    s.SetHtml("<span style=\"color:#fe5d63;\">" + data.ToString(format) + houzui + "</span>");
                }
                else
                {
                    s.SetHtml("<span style=\"color:#0aaa00;\">" + data.ToString(format) + houzui + "</span>");
                }
                return s;
            }
            catch
            {
                if (def != "" && def != isnull)
                {
                    s.SetHtml(def + houzui);
                }
                else
                {
                    s.SetHtml(isnull);
                }
                return s;
            }
        }

        /// <summary>
        /// 获取Decimal的正数或小数
        /// </summary>
        /// <param name="d"></param>
        /// <param name="flag">1：返回正数 2：返回小数</param>
        /// <returns></returns>
        public static string FormatDecimal2(decimal? d, int flag)
        {
            if (d != null)
            {
                switch (flag)
                {
                    case 1:
                        return d.Value.ToString().Split('.')[0];
                    case 2:
                        if (d.Value.ToString().IndexOf(".") > -1)
                        {
                            return string.Concat(".", d.Value.ToString().Split('.')[1]);
                        }
                        else
                        {
                            return string.Empty;
                        }
                    default:
                        return string.Empty;
                }
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 格式化日期
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string FormatDateTime(DateTime? dt, string format = "yyyy-MM-dd")
        {
            if (dt == null)
            {
                return string.Empty;
            }
            else
            {
                return dt.Value.ToString(format);
            }
        }

        /// <summary>
        /// 格式化日期-新（今天、昨天、今年的日期显示格式 M-d HH:mm:ss）
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string FormatDateTimeNew(DateTime? dt, string timeFormat = "HH:mm:ss",
            string curYearDateTimeFormat = "M-d HH:mm:ss",string datetimeFormat = "yyyy-M-d HH:mm:ss")
        {
            if (dt == null)
            {
                return string.Empty;
            }

            DateTime dtNow = DateTime.Now;

            if (dt.Value.Date == dtNow.Date)
            {
                return string.Concat("今天 ", FormatDateTime(dt, timeFormat));
            }
            else if (dt.Value.Date == dtNow.AddDays(-1).Date)
            {
                return string.Concat("昨天 ", FormatDateTime(dt, timeFormat));
            }
            else if (dt.Value.Year == dtNow.Year)
            {
                return FormatDateTime(dt, curYearDateTimeFormat);
            }
            else
            {
                return FormatDateTime(dt, datetimeFormat);
            }
        }

        /// <summary>
        /// 通过传入的月份得到月的第一天及月的最后一天
        /// </summary>
        /// <param name="month">格式 yyyyMM</param>
        /// <param name="firstDay"></param>
        /// <param name="lastDay"></param>
        public static void FormatMonth(string month, out DateTime firstDay, out DateTime lastDay)
        {
            firstDay = DateTime.MinValue;
            lastDay = DateTime.MinValue;

            if (!string.IsNullOrEmpty(month) && month.Length == 6)
            {
                if (DateTime.TryParse(string.Concat(month.Substring(0, 4), "-", month.Substring(4, 2), "-1"), out firstDay))
                {
                    lastDay = firstDay.AddMonths(1).AddDays(-1);
                }
            }
        }

        /// <summary>
        /// 取得不重复的10位数字序列
        /// 取得日期的年月日时分秒毫秒+Guid生成的10位数字
        /// </summary>
        /// <returns></returns>
        public static string GenerateIntID(string pre = "")
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            return pre + DateTime.Now.ToString("yyyyMMddHHmmssFFF").PadRight(17, '0')
                + Math.Abs(BitConverter.ToInt32(buffer, 0)).ToString().PadLeft(10, '0');
        }

        /// <summary>
        /// 获取16位唯一字符串
        /// </summary>
        /// <returns></returns>
        public static string GetUniqueNo()
        {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
            {
                i *= ((int)b + 1);
            }
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }

        /// <summary>
        /// 格式化星期
        /// </summary>
        /// <param name="dayofweek"></param>
        /// <returns></returns>
        public static string FormatDayOfWeek(DayOfWeek dayofweek)
        {
            switch (dayofweek)
            {
                case DayOfWeek.Friday:
                    return "周五";
                case DayOfWeek.Monday:
                    return "周一";
                case DayOfWeek.Saturday:
                    return "周六";
                case DayOfWeek.Sunday:
                    return "周日";
                case DayOfWeek.Thursday:
                    return "周四";
                case DayOfWeek.Tuesday:
                    return "周二";
                case DayOfWeek.Wednesday:
                    return "周三";
                default:
                    return string.Empty;
            }
        }

        /// <summary>
        /// 格式化长文本
        /// </summary>
        /// <param name="str"></param>
        /// <param name="maxCount"></param>
        /// <returns></returns>
        public static string StringSubstrLen(string str, int len)
        {
            if (string.IsNullOrEmpty(str))
            {
                return string.Empty;
            }

            byte[] bytes = System.Text.Encoding.Unicode.GetBytes(str);
            int n = 0;  //  表示当前的字节数
            int i = 0;  //  要截取的字节数
            for (; i < bytes.GetLength(0) && n < len; i++)
            {
                //  偶数位置，如0、2、4等，为UCS2编码中两个字节的第一个字节

                if (i % 2 == 0)
                {
                    n++;      //  在UCS2第一个字节时n加1
                }
                else
                {
                    //  当UCS2编码的第二个字节大于0时，该UCS2字符为汉字，一个汉字算两个字节
                    if (bytes[i] > 0)
                    {
                        n++;
                    }
                }
            }

            //  如果i为奇数时，处理成偶数
            if (i % 2 == 1)
            {
                //  该UCS2字符是汉字时，去掉这个截一半的汉字 
                if (bytes[i] > 0)
                {
                    i = i - 1;
                }
                //  该UCS2字符是字母或数字，则保留该字符
                else
                {
                    i = i + 1;
                }
            }
            
            string result = System.Text.Encoding.Unicode.GetString(bytes, 0, i);

            if (result.Length < str.Length)
            {
                return result + "...";
            }
            else
            {
                return result;
            }
        }

        /// <summary>
        /// 根据连登天数获取I豆奖励数量
        /// </summary>
        /// <param name="loginDays"></param>
        /// <returns></returns>
        public static int GetContinueLoginINum(int loginDays)
        {
            int iNum = 0;

            switch (loginDays)
            {
                case 1:
                    iNum = 5;
                    break;
                case 2:
                    iNum = 10;
                    break;
                case 3:
                    iNum = 15;
                    break;
                case 4:
                    iNum = 20;
                    break;
                case 5:
                    iNum = 25;
                    break;
                default:
                    break;
            }

            return iNum;
        }

        public static string GetGuessClass(int type)
        {
            string ret = string.Empty;

            switch (type)
            {
                case 0:
                    ret = "b_1_22";
                    break;
                case 1:
                    ret = "b_1_2";
                    break;
                case -1:
                    ret = "b_1_222";
                    break;
                default:
                    break;
            }

            return ret;
        }

        /// <summary>
        /// 格式化竞猜方向
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string FormatGuessType(int type)
        {
            string ret = string.Empty;

            switch (type)
            {
                case 0:
                    ret = "看跌";
                    break;
                case 1:
                    ret = "看涨";
                    break;
                default:
                    break;
            }

            return ret;
        }

        /// <summary>
        /// 格式化竞猜结果
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public static string FormatGuessResult(int result)
        {
            string ret = string.Empty;

            switch (result)
            {
                case 0:
                    ret = "很遗憾，竞猜失败";
                    break;
                case 1:
                    ret = "恭喜您，竞猜成功";
                    break;
                case -1:
                    ret = "复活晋级";
                    break;
                default:
                    break;
            }

            return ret;
        }

        /// <summary>
        /// 格式化手机号码加星显示
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public static string FormatMobile(string mobile)
        {
            if (string.IsNullOrEmpty(mobile))
            {
                return string.Empty;
            }
            if (mobile.Length != 11)
            {
                return mobile;
            }

            return string.Concat(mobile.Substring(0,3), "****", mobile.Substring(7,4));
        }

        /// <summary>
        /// 格式化涨跌幅字体颜色
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static System.Web.IHtmlString FormatQQColor(decimal c)
        {
            if (c >= 0)
            {
                return new HtmlString("red");
            }
            else
            {
                return new HtmlString("green");
            }
        }

        /// <summary>
        /// Unicode转字符串
        /// </summary>
        /// <param name="utxt"></param>
        /// <returns></returns>
        public static string UnicodeToStr(string utxt)
        {
            if (string.IsNullOrEmpty(utxt))
            {
                return string.Empty;
            }

            string ret = string.Empty;
            string[] strlist = utxt.Replace("//", "").Split('u');

            try
            {
                for (int i = 1; i < strlist.Length; i++)
                {
                    //将unicode字符转为10进制整数，然后转为char中文字符  
                    ret += (char)int.Parse(strlist[i], System.Globalization.NumberStyles.HexNumber);
                }
            }
            catch (FormatException ex)
            {
                LogManager.DefaultLogger.Error(ex, "Unicode转字符串失败");
            }

            return ret;
        }

        /// <summary>
        /// 获取32位唯一字符串
        /// </summary>
        /// <returns></returns>
        public static string GetRequestTID()
        {
            string tid = Guid.NewGuid().ToString("N");

            if (!string.IsNullOrEmpty(tid))
            {
                CacheManager.DefaultCache.Set<string>(tid, tid, 10);
            }

            return tid;
        }

        /// <summary>
        /// 格式化QQ炒股大赛股票代码
        /// </summary>
        /// <param name="stockname"></param>
        /// <returns></returns>
        public static string FormatQQStockCode(string stockcode)
        {
            string ret = string.Empty;

            if (!string.IsNullOrEmpty(stockcode))
            {
                ret = stockcode.Replace("sh", "");
                ret = ret.Replace("sz", "");
            }

            return ret;
        }

        /// <summary>
        /// 格式化QQ炒股大赛交易方向
        /// </summary>
        /// <param name="direction"></param>
        /// <returns></returns>
        public static string FormatTradeDirection(string direction)
        {
            string ret = string.Empty;

            if (!string.IsNullOrEmpty(direction))
            {
                switch (direction)
                {
                    case "buy":
                        ret = "买入";
                        break;
                    case "sell":
                        ret = "卖出";
                        break;
                    default:
                        break;
                }
            }

            return ret;
        }

        /// <summary>
        /// 格式化QQ炒股大赛交易方向颜色
        /// </summary>
        /// <param name="direction"></param>
        /// <returns></returns>
        public static System.Web.IHtmlString FormatTradeDirectionColor(string direction)
        {
            if (!string.IsNullOrEmpty(direction))
            {
                switch (direction)
                {
                    case "buy":
                        return new HtmlString("red");
                    case "sell":
                        return new HtmlString("green");
                    default:
                        break;
                }
            }

            return null;
        }

        /// <summary>
        /// 获取相应的yidata
        /// </summary>
        /// <param name="qq"></param>
        /// <returns></returns>
        public static string GetYiData(string qq)
        {
            string tid = GetRequestTID();
            string yidata = "{\"qq\":\"" + qq + "\",\"requestid\":\"" + tid + "\"}";
            yidata = EncryptionUtil.EncryptIt(yidata, ConfigHelper.AES_KEY, ConfigHelper.AES_IV);
            return System.Web.HttpUtility.UrlEncode(yidata);
        }

        public static string FormatUserName(string username)
        {
            
            if (username.IndexOf("加q", StringComparison.OrdinalIgnoreCase) > -1)
            {
                username = username.Replace("加q", "**");
                username = username.Replace("加Q", "**");
            }
            else if (username.IndexOf("加群", StringComparison.OrdinalIgnoreCase) > -1)
            {
                username = username.Replace("加群", "**");
            }
            else if (username.IndexOf("加扣", StringComparison.OrdinalIgnoreCase) > -1)
            {
                username = username.Replace("加扣", "**");
            }
            else if (username.IndexOf("扣", StringComparison.OrdinalIgnoreCase) > -1)
            {
                username = username.Replace("扣", "*");
            }
            else if (username.IndexOf("群", StringComparison.OrdinalIgnoreCase) > -1)
            {
                username = username.Replace("群", "*");
            }
            else if (username.IndexOf("q", StringComparison.OrdinalIgnoreCase) > -1)
            {
                username = username.Replace("q", "*");
                username = username.Replace("Q", "*");
            }           

            return username;
        }
    }
}
